<template>
    <div class="product_selection">
        <div class="page_img"></div>
        <div class="header">
            <van-nav-bar class="nav_bar" title="补样审批" left-text="" left-arrow @click-left="handleBack" />
        </div>

        <div class="product_selection_header">
            <div style="" class="product_list_serch-text">
                <van-search class="product_list_serch1" placeholder="请输入商品名称" @search="onSearch" v-model="searchValue"
                    shape="round" clearable>
                    <template #left-icon>
                        <div class="search_l_bt"></div>
                    </template>
                    <template #right-icon>
                        <div class="search_r_bt" @click="onSearch">搜索</div>
                    </template>
                </van-search>

            </div>
            <div class="product_selection_header_nav">
                <div class="nav_box">
                    <div v-for="item in navList" :key="item.value"
                        :class="{ nav_box_item: true, nav_box_item_active: item.value === queryParams.status }"
                        @click="navClick(item.value)">
                        {{ item.name }}
                    </div>
                </div>
            </div>
        </div>
        <div class="commodity_classify">
            <div class="commodity_classify_items" @click="categoryIsShow = true">
                <span>{{ queryParams.categoryIdList.length ? '多品类' : '商品类目' }}</span>
                <img src="@/assets/commodity/icon_heisexiasanjiao.png" alt="">
            </div>
            <category :isShow="categoryIsShow" v-model:value="queryParams.categoryIdList" :multiple="true"
                @leftClick="categoryIsShow = false" @onSubmit="categorySubmit" />
            <div class="home-dates-box flex-align-center b-box" @click="showCalendar = true">
                <div class="flex-align-center">
                    <div class="home-index-data-date-first">
                        <div class="home-index-data-date-first-date">
                            {{ queryParams.outStartTime }}
                        </div>
                    </div>
                    <div class="line"></div>
                    <div class="home-index-data-date-second">
                        <div class="home-index-data-date-second-date">
                            {{ queryParams.outEndTime }}
                        </div>
                    </div>
                </div>

                <div class="r_img"></div>
            </div>
            <van-calendar v-model:show="showCalendar" switch-mode="year-month" allow-same-day type="range"
                @confirm="onConfirmCalendar" />

        </div>
        <div class="product_selection_list">
            <van-pull-refresh style="height: 100%;" v-model="refreshing" @refresh="onRefresh">
                <van-list v-model:loading="loading" :finished="finished" @load="onLoad">
                    <template v-slot:finished>
                        <div class="nothing_div" v-if="list.length == 0">
                            <van-image :src="nothingData"></van-image>
                            <div class="nothing_font">暂无数据</div>
                        </div>
                    </template>
                    <div class="product_list_van_list">
                        <div v-for="item in list" :key="item.id">
                            <ListItems :isTime="true" :row="item" :status="Number(queryParams.status)"
                                @click="handleGetDetails(item)" />
                            <div class="list_line"></div>
                        </div>
                    </div>
                </van-list>
            </van-pull-refresh>
        </div>
    </div>
</template>
<script setup lang="ts" name="productSelection">
import { onMounted, ref, watch, onUnmounted, onActivated } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import nothingData from '@/assets/porduct/icon_zanwushuju.png'
import { getSampleList } from '@/api/operation/index'
import ListItems from './components/listItemsNewui.vue'
// 类目
import category from '@/components/category/index.vue'
const route = useRoute();
const router = useRouter();
const defaultPhoneHeight = ref(0) //屏幕默认高度
const nowPhoneHeight = ref(0) //屏幕现在的高度
const vantListScrollTop = ref<any>(0) // 列表滚动高度
const searchValue = ref("");
const navList = ref([{ name: '审批中', value: 0 }, { name: '已通过', value: 2 }, { name: '已驳回', value: 1 }])
const refreshing = ref(false);
// 此处定义了两个loading，loadingBox是针对页面加载进行定义的loading，loading是针对列表加载状态定义的loading，列表loading不能写在try中，不然会导致页面接口重复刷新
const loadingBox = ref(false)
const loading = ref(false);
const finished = ref(false);
const list = ref<any[]>([]);
// 计算当前日期的前六天
const calculateDateSevenDaysAgo = () => {
    const today = new Date()
    today.setDate(today.getDate() - 6)
    return today.toISOString().split('T')[0] // 格式化为 YYYY-MM-DD
}
// 当前日期
const currentDateBottom = () => {
    const today = new Date()
    today.setDate(today.getDate())
    return today.toISOString().split('T')[0] // 格式化为 YYYY-MM-DD
}
const queryParams = ref<any>({
    pageNum: 1,
    pageSize: 10,
    styleName: '', // 商品名称
    status: 0, // 审批状态
    categoryIdList: [], // 类目
    outStartTime: calculateDateSevenDaysAgo(),// 开始时间
    outEndTime: currentDateBottom(),// 结束时间
});
// 类目开关
const categoryIsShow = ref(false)
// 限制连续刷新数据重复问题
const refreFlag = ref(true)

const emits = defineEmits(['doShow'])
// 在组件挂载完成后添加事件监听器
onMounted(() => {
    defaultPhoneHeight.value = window.innerHeight;
    // 添加事件监听器
    window.addEventListener('resize', handleResize);
    functionScroll('init')
    if (route.query.status) {
        queryParams.value.status = route.query.status
    }
})
// 处理窗口大小变化的函数
const handleResize = () => {
    nowPhoneHeight.value = window.innerHeight;
};
// 在组件卸载前移除事件监听器
onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
    functionScroll('delete')
});
watch(nowPhoneHeight, () => {
    if (defaultPhoneHeight.value != nowPhoneHeight.value) {
        // 当软键盘弹出,改变bottomIsSHow变量然后去控制bottom的显示与隐藏
        emits('doShow', false)
    } else {
        // 相等代表软键盘收起后,与上同理
        emits('doShow', true)
    }
})

/** 查询商品列表 */
const getList = async () => {
    // 无合同审批
    try {
        var res = await getSampleList(queryParams.value);
        setTimeout(() => {
            refreFlag.value = true
            // 空数据 停止加载
            if (res.rows.length == 0) {
                list.value = [];
                finished.value = true;
                loading.value = false;
                loadingBox.value = false
                return;
            }
            // 有数据 赋值列表 加载状态结束
            res.rows.forEach((item) => {
                finished.value = false;
                list.value.push(item);
            });
            loading.value = false;
            loadingBox.value = false
            refreshing.value = false;
            // 如果list长度大于等于总数据条数，数据全部加载完成
            if (list.value.length >= res.total) {
                finished.value = true; //结束加载
            }
        }, 400);
    } catch (error) {
        loadingBox.value = false
    }
};
/** 加载更多 */
const onLoad = async () => {
    loadingBox.value = true
    getList();
    queryParams.value.pageNum++;
};
/** 下拉 */
const onRefresh = () => {
    if (refreFlag.value) {
        refreFlag.value = false
        finished.value = false; // 清空列表数据
        refreshing.value = false;
        loading.value = true; // 加载状态
        queryParams.value.pageNum = 1; // 分页数赋值为1
        list.value = []; // 清空数组
        onLoad(); // 重新加载数据
    } else {
        finished.value = false;
        refreshing.value = false;
    }
};

/** nav点击切换事件 */
const navClick = async (value: number) => {
    searchValue.value = ''
    queryParams.value.styleName = ''
    queryParams.value.status = value
    queryParams.value.categoryIdList = []
    queryParams.value.outStartTime = calculateDateSevenDaysAgo()
    queryParams.value.outEndTime = currentDateBottom()
    onRefresh()
}
/** 跳转详情 */
const handleGetDetails = (row: any) => {
    router.push({
        path: '/operationApprovalDetails',
        query: {
            id: row.id,
            status: queryParams.value.status
        }
    })
}

/** 根据商品名称搜索 */
const onSearch = () => {
    queryParams.value.styleName = searchValue.value
    onRefresh()
}

// 缓存组件中保存页面浏览位置方法
const functionScroll = (type: string) => {
    const dom: any = document.querySelector('.van-pull-refresh')
    if (type === 'init') {
        dom?.addEventListener('scroll', (e: any) => {
            vantListScrollTop.value = e.target.scrollTop
        })
    } else if (type === 'delete') {
        dom?.removeEventListener('scroll', () => { });
    } else if (type === 'black') {
        dom.scrollTop = vantListScrollTop.value
    }
}
// 商品类目选择完成
const categorySubmit = () => {
    categoryIsShow.value = false
    onRefresh()
}

/** 返回 */
const handleBack = () => {
    router.push('/operation/operateMine')
}

onActivated(() => {
    functionScroll('black')
})

//================================日历==============
const showCalendar = ref(false);
const formatDate = (date) => `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
const onConfirmCalendar = (values) => {
    const [start, end] = values;
    showCalendar.value = false;
    queryParams.value.outStartTime = formatDate(start)
    queryParams.value.outEndTime = formatDate(end)
    onRefresh()
};


</script>

<script lang="ts">
export default { name: 'operationApproval' }
</script>
<style lang="less" scoped>
.product_selection {
    width: 100%;
    height: 100vh;
    background-color: #fff;
    background: url("@/assets/newui/productList/icon_shangpinbeijing@2x.png");
    background-size: 100%;
    background-repeat: no-repeat;
    display: flex;
    flex-flow: column;
    position: relative;

    .page_img {
        background: url("@/assets/newui/productList/icon_shenpitu@2x.png");
        background-size: 100% 100%;
        position: absolute;
        width: 60px;
        height: 60px;
        top: 44px;
        right: 63px;

    }

    .header {
        filter: blur(0px);
        height: 90px;
        padding-top: 44px;
        box-sizing: border-box;
        width: 100%;
        position: relative;
        z-index: 6003;

        :deep(.van-icon-arrow-left) {
            color: #1a1b1c !important;
        }

        :deep(.van-nav-bar__title) {
            color: #1a1b1c !important;
            font-size: 18px !important;
            font-weight: 600 !important;
        }

        :deep(.van-nav-bar) {
            background: none !important;

            &::after {
                display: none !important;
            }
        }

        :deep(.van-nav-bar__content) {
            background-color: transparent !important;
        }
    }

    .commodity_classify {
        width: 100%;
        height: 44px;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: space-between;
        background: #fff;
        margin-top: 10px;
        position: relative;
        border-radius: 15px 15px 0px 0px;
        padding: 0 10px;

        .commodity_classify_items {
            width: 110px;
            display: flex;
            align-items: center;
            justify-content: center;

            img {
                width: 10px;
                height: 6px;
                margin-left: 5px;
            }

            span {
                flex: 0.7;
                min-width: 0;
                text-overflow: ellipsis;
                overflow: hidden;
                white-space: nowrap;
                text-align: right;
            }
        }

        .commodity_classify_item {
            display: flex;
            align-items: center;
            justify-content: center;
            flex: 1;
            min-width: 0;

            img {
                width: 10px;
                height: 6px;
                margin-left: 5px;
            }

            span {
                flex: 0.7;
                min-width: 0;
                text-overflow: ellipsis;
                overflow: hidden;
                white-space: nowrap;
                text-align: right;
            }
        }

        .commodity_classify_div {
            flex: 0.3;
            margin-left: 10px;

            img {
                width: 16px;
                height: 18px;
            }
        }
    }

    .home-dates-box {
        font-family: PingFangSC, PingFang SC;
        font-weight: 500;
        font-size: 12px;
        color: #0094FF;
        line-height: 12px;
        text-align: left;
        font-style: normal;
        width: 222px;
        height: 26px;
        background: #EEF0FF;
        border-radius: 5px;
        border: 1px solid #FFFFFF;
        filter: blur(0px);
        justify-content: space-between;
        padding-left: 10px;

        .line {
            width: 20px;
            height: 1px;
            background: #0094FF;
            margin-right: 5px;
        }

        .r_img {
            background: url("@/assets/newui/home/icon_rili@2x.png") no-repeat;
            background-size: 100% 100%;
            width: 24px;
            height: 24px;
        }
    }


    .product_selection_header {
        width: 100%;
        box-sizing: border-box;

        :deep .van-search__field {
            background-color: #fff;
            border-radius: 20px;
        }

        .product_list_serch-text {
            display: flex;
            align-items: center;
            width: 100%;
            position: relative;
            box-sizing: border-box;
            padding: 0 15px;
        }

        .product_list_serch1 {
            display: flex;
            align-items: center;
            width: 100%;
            height: 34px;
            padding: 0px;
            box-sizing: border-box;
            overflow: hidden;
            background-color: #fff;
            border: 1px solid #0094ff;
            border-radius: 20px;

            :deep .van-search__content {
                height: 35px;
                background-color: #fff;
            }

            :deep .van-search__field {
                height: 35px;
            }

            :deep .van-field__clear {
                right: 0px !important;
            }

            .search_l_bt {
                width: 14px;
                height: 14px;
                background-image: url("@/assets/newui/productList/icon_sousuo@2x.png");
                background-size: 100% 100%;
            }

            .search_r_bt {
                width: 54px;
                height: 26px;
                background: linear-gradient(146deg, #0064ff 0%, #008fff 100%);
                border-radius: 14px;
                font-weight: 500;
                font-size: 14px;
                color: #ffffff;
                line-height: 26px;
                text-align: center;
                transform: translateX(5px);
            }
        }


        .product_selection_header_nav {
            width: 100%;
            padding: 0 32px;
            margin-top: 10px;
            box-sizing: border-box;

            .nav_box {
                width: 100%;
                display: flex;
                align-items: center;
                background: #fff;
                border-radius: 18px;
                padding: 2px;
                box-sizing: border-box;

                .nav_box_item {
                    height: 31px;
                    flex: 1;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    border-radius: 16px;
                    font-weight: 400;
                    font-size: 14px;
                    color: #1A1B1C;
                }

                .nav_box_item_active {
                    background: linear-gradient(270deg, #0064FF 0%, #008FFF 100%);
                    font-weight: 500;
                    color: #FFFFFF;
                }
            }
        }
    }

    .product_selection_list {
        flex: 1;
        min-height: 0;
    }

    :deep(.van-pull-refresh) {
        overflow: scroll;
    }
}

.list_line {
    height: 8px;
    background: #F6FAFF;
}
</style>